local ChannelBase = import(".ChannelBase")
local ChannelPwrd = class("ChannelPwrd", ChannelBase)

function ChannelPwrd:ctor()
    self.super.ctor(self)
    self._loginParams = {}
end

function ChannelPwrd:_init()
    app:addCustomEventListener("CHANNEL_LOGIN_EVENT", function(event)
		local param = event:getUserStr()
		self:loginCallback(param)
    end)
    app:addCustomEventListener("CHANNEL_SWITCH_ACCOUT_EVENT", function(event)
		local param = event:getUserStr()
		self:switchAccoutCallback(param)
    end)
    app:addCustomEventListener("CHANNEL_PRODUCT_LIST_EVENT", function(event)
		local param = event:getUserStr()
		self:getProductListCallback(param)
    end)
    app:addCustomEventListener("CHANNEL_PAY_EVENT", function(event)
		local param = event:getUserStr()
		self:payCallback(param)
    end)
end

function ChannelPwrd:getChannelTag()
	return app:getChannelTag()
end

function ChannelPwrd:getChannelId()
	return "pwrd"
end

function ChannelPwrd:getAccount()
    if self._loginParams and self._loginParams.account then
        return self._loginParams.account
    end
    return ""
end

function ChannelPwrd:_login()  
    self:showLoginView()
    if app:isAndroid() then
        self.callJava("()V", "login")
    elseif app:isIOS() then
        self.callOC("login")
    end
end

function ChannelPwrd:_logout()
    if app:isAndroid() then
        self.callJava("()V", "logout")
    elseif app:isIOS() then
        self.callOC("logout")
    end
end

function ChannelPwrd:_switchAccount()
    if app:isAndroid() then
        self.callJava("()V", "switchAccount")
    elseif app:isIOS() then
        self.callOC("switchAccount")
    end
end

function ChannelPwrd:getUniqueIds()
    local ok, ret
    if app:isAndroid() then
        ok, ret = self.callJava("()V", "getUniqueIds")
    elseif app:isIOS() then
        ok, ret = self.callOC("getUniqueIds")
    end
    print("--------->>>getUniqueIds", ret)
    return ret
end

function ChannelPwrd:_joinUrl(host)
    local channelId = self:getChannelId()
    local channelTag = self:getChannelTag()
    local op_id = self:getUniqueIds()
    local token = self._loginParams.accessToken
    local account = self._loginParams.account
    if account == nil then
        local loginParamsStr
        if self._loginParams then
            loginParamsStr = json.encode(self._loginParams)
        end
        loginParamsStr = loginParamsStr or ""
        assert(false,"getAccount nil "..loginParamsStr)
    end

    local url = host.."gamelogin?".."channel="..channelId
    if channelTag then
        url = url.."&channeltag="..channelTag
    end
    if op_id then
        url = url.."&op_id="..op_id
    end
    if account then
        url = url.."&account="..account
    end
    if token then
        url = url.."&token="..token
    end
    print("---------------pwrd ChannelPwrd:jointUrl()",url)
    return url
end

-- 角色打点
function ChannelPwrd:roleTrackEvent(params)
    if not params then
        return
    end
    dump(params, "channelpwrd roleTrackEvent params")
    local jstr = json.encode(params)
    if app:isAndroid() then
        self.callJava("(Ljava/lang/String;)V", "roleTrackEvent", jstr)
    elseif app:isIOS() then
        self.callOC("roleTrackEvent", {jsonStr = jstr}) 
    end
end

-- 完美打点
function ChannelPwrd:wanmeiTrackEvent(params)
    if not params then
        return
    end
    dump(params, "channelpwrd wanmeiTrackEvent params")
    local jstr = json.encode(params)
    if app:isAndroid() then
        self.callJava("(Ljava/lang/String;)V", "wanmeiTrackEvent", jstr)
    elseif app:isIOS() then
        self.callOC("wanmeiTrackEvent", {jsonStr = jstr}) 
    end
end

-- 广告打点
function ChannelPwrd:trackEventAD(params)
    if not params then
        return
    end
    if not params.uid then
        params.uid = self:getAccount()
    end
    dump(params, "channelpwrd trackEventAD params")
    local jstr = json.encode(params)
    if app:isAndroid() then
        self.callJava("(Ljava/lang/String;)V", "trackEventAD", jstr)
    elseif app:isIOS() then
        self.callOC("trackEventAD", {jsonStr = jstr}) 
    end
end

-- 资源打点
function ChannelPwrd:wanmeiGameEvent(params)
    if not params then
        return
    end
    dump(params, "channelpwrd wanmeiGameEvent params")
    local jstr = json.encode(params)
    if app:isAndroid() then
        self.callJava("(Ljava/lang/String;)V", "wanmeiGameEvent", jstr)
    elseif app:isIOS() then
        self.callOC("wanmeiGameEvent", {jsonStr = jstr})
    end
end

function ChannelPwrd:loginCallback(jsonStr)
    print("------------->>>>>channelpwrd loginCallback")
    local obj = json.decode(jsonStr)
    dump(obj, "channelpwrd loginCallback obj")
    if obj then
        if obj.errCode == nil then
            self._loginParams = obj
            release_print("================>> pwrdsdklogin success")
            self:hideLoginView()
            self:_onLoginSuccess()
        else
            self:_onLoginFail(obj.errCode)
        end
    else
        self:_onLoginFail("unknown error")
    end
end

function ChannelPwrd:switchAccoutCallback()
    release_print("------------>>>>>channelpwrd switchAccoutCallback")
    self._loginParams = {}
    app.session:clearLogined()
    self:_onLogoutSuccess()
end

-- 获取商品列表
function ChannelPwrd:getPayGoods(cb)
    self._getPayGoods = cb
    local productIds = {} -- 商品ID列表
    app.session:request("pb_recharge.C2S_QueryRechargeGoods", {}, function(ret)
        -- dump(ret, "S2C_QueryRechargeGoods")
        if not ret then
            self:_onGetProductListFail()
            return 
        end
        self._goodsList = {} -- 商品列表
        local goods = self:_clonePayGoodsInfo(ret.RechargeGoodsInfos)
        self._goodsList.RechargeGoodsInfos = goods
        self._goodsMap = {}
        for k, v in pairs(goods or {}) do
            self._goodsMap[v["product_id"]] = v
            table.insert(productIds, v["product_id"])
        end
        -- dump(productIds, "channelpwrd getProductList productIds---->>>")
        local params = {}
        params.productIds = productIds
        local jstr = json.encode(params)
        if app:isAndroid() then
            self.callJava("(Ljava/lang/String;)V", "getProductList", jstr)
        elseif app:isIOS() then
            self.callOC("getProductList", {jsonStr = jstr})
        end
    end)
end

function ChannelPwrd:getProductListCallback(jsonStr)
    print("------------>>>>>channelpwrd getProductListCallback")
    local obj = json.decode(jsonStr)
    if obj then
        if obj.ret == 1 then
            self:_onGetProductListFail()
        else
            self:_onGetProductListSuccess(obj.data)
        end
    else
        release_print("parse json fail")
    end
end

function ChannelPwrd:_onGetProductListSuccess(dataArr)
    print("===========>>> channelpwrd _onGetProductListSuccess")
    local data = {}
    local fixGoods = {}
    for k, v in pairs(dataArr or {}) do
        local product_id = v["productId"]
        if self._goodsMap[product_id] then
            local price = v.price
            if app:isIOS() and v.price_currency_symbol then -- ios要加上货币符号
                price = v.price_currency_symbol .. v.price
            end
            self._goodsMap[product_id].price = price
        else
            release_print("can not find product_id ", product_id)
        end
    end
    for k, v in pairs(self._goodsMap) do
        table.insert(fixGoods, v)
    end
    data.RechargeGoodsInfos = fixGoods
    if self._getPayGoods then
        self._getPayGoods("success", data)
    end
end 

function ChannelPwrd:_onGetProductListFail()
    print("============>>>> channelpwrd get product list fail")
    -- self._sdkCanPay = false
    if self._getPayGoods then
        self._getPayGoods("fail", self._goodsList)
    end
    self._getPayGoods = nil
end

function ChannelPwrd:_pay(payData)
    local params = {
        productId = payData.productId,
        quantity = 1,
        orderId = payData.orderID,
        roleId = UD.player.uid,
        serverId = tostring(app.session:getZoneId()),
        sendGoodsUrl = payData.sendGoodsUrl,
        extraInfo = -1,
    }
    -- dump(params, "channlepwrd pay params---->>>>")
    if app:isAndroid() then
        local jstr = json.encode(params)
        self.callJava("(Ljava/lang/String;)V", "pay", jstr)
    elseif app:isIOS() then
        self.callOC("pay", params)
    end
end

function ChannelPwrd:payCallback(ret)
    local code = tonumber(ret)
    release_print("=====>> channelpwrd pay call back ret "..(ret or ""))
    if code == Enums.PayRetState.success then
        self:_onPaySuccess()
    else
        self:_onPayFail(code)
    end
end

function ChannelPwrd:showLoginView()
	if not self._view then
		local view = require("app.login.views.PwrdLoginView").new()
		cc.Director:getInstance():getRunningScene():addChild(view, 1000)
		self._view = view
		view:onOperate(function(op, sender)
            if op == "pwrd" then
                if self._loginCallback then
                    self:login(self._loginCallback)
                end
			end
			sender:enableButtons(false)
		end)
	end
	self._view:setVisible(true)
	self._view:enableButtons(true)
end

function ChannelPwrd:hideLoginView()
	if self._view then
		self._view:removeFromParent()
		self._view = nil
	end
end

return ChannelPwrd